// tslint:disable-next-line:max-line-length
import { Component, OnInit, TemplateRef, Input, Output, EventEmitter, ViewChild, ComponentFactoryResolver, ViewContainerRef, AfterContentInit } from '@angular/core'
import { INewPageColumn } from '@shared/interfaces/common'
import { NzMessageService } from 'ng-zorro-antd'
import { NewPageDirective } from './new-page.directive'
import { Router, ActivatedRoute } from '@angular/router'
import { Location } from '@angular/common'

@Component({
  selector: 'app-new-page',
  templateUrl: './new-page.component.html',
  styleUrls: ['./new-page.component.less'],
})
export class NewPageComponent implements OnInit {

  @ViewChild(NewPageDirective) appNewContent: NewPageDirective

  componentRef: any

  _index = 0

  length: number

  percent = 0

  @Input()
  pages: INewPageColumn[]

  @Output()
  selfSubmit = new EventEmitter()

  constructor(
    public router: Router,
    public route: ActivatedRoute,
    public location: Location,
    private msg: NzMessageService,
    private componentFactoryResolver: ComponentFactoryResolver,
  ) {}

  get index() {
    return this._index
  }

  set index(index) {
    this._index = index
    this.percent = this.calPercent()
  }

  ngOnInit() {
    this.length = this.pages.length
    this.percent = this.calPercent()
    this.loadComponent()
  }

  loadComponent() {
    const com = this.pages[this.index].component

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(com.component)

    const viewContainerRef = this.appNewContent.viewContainerRef
    viewContainerRef.clear()

    this.componentRef = viewContainerRef.createComponent(componentFactory)

    this.componentRef.instance.data = com.data
  }

  goLeave(): void {
    this.location.back()
  }

  goBack() {
    if (this.index > 0) {
      this.index--
      this.componentRef.instance.pushDataToStore()
      this.loadComponent()
    } else console.error('已经是第一层级，无法往上，button 渲染错误')
  }

  goNext() {
    if (!this.componentRef.instance.checkValid) {
      this.msg.error('校验方法未实现')
      return
    }
    const valid = this.componentRef.instance.checkValid()
    if (valid && this.index < this.length - 1) {
      this.index++
      this.loadComponent()
    } else {
      console.error('已经是最后一层级，无法往下，button 渲染错误')
    }
  }

  goSubmit(): void {
    if (!this.componentRef.instance.checkValid) {
      this.msg.error('校验方法未实现')
      return
    }
    const valid = this.componentRef.instance.checkValid()
    if (!valid) {
      return
    }

    if (this.componentRef.instance.payload) {
      this.selfSubmit.emit(this.componentRef.instance.payload)
      return
    }

    this.selfSubmit.emit()
  }

  private calPercent() {
    return (this.index + 1) / this.length * 100
  }
}
